package org.darkforest.admin.interceptor;

import org.darkforest.ucenter.auth.AuthPassport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by valentina on 15/3/6.
 * pc端权限验证
 */
public class AuthBySessionInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(AuthBySessionInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean filter = true;
        String url = request.getServletPath();
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            //没有声明需要权限,或者声明不验证权限
                if(request.getSession().getAttribute("memInfo")==null){
                    String basePath = (String)request.getSession().getServletContext().getAttribute("basePath");
                    request.getSession().setAttribute("reUrl", url);
                    response.sendRedirect(basePath+"/login?reUrl="+url);
                    filter = false;
                }else {
                    if(authPassport == null || authPassport.isLogin() == true){
                        filter = true;
                    }
                }
        }
        return filter;
    }
}
